package com.zl.tcbnewcar.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.TabLayout;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.socialize.UMShareAPI;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.zhy.autolayout.AutoLinearLayout;
import com.zl.tcbnewcar.R;
import com.zl.tcbnewcar.base.BaseActivity;
import com.zl.tcbnewcar.base.UniversalAdapter;
import com.zl.tcbnewcar.base.UniversalViewHolder;
import com.zl.tcbnewcar.model.CarCommentEntity;
import com.zl.tcbnewcar.model.CarServerEntity;
import com.zl.tcbnewcar.model.CarServerResourceEntity;
import com.zl.tcbnewcar.model.ShareBean;
import com.zl.tcbnewcar.ui.dialog.ImagePreviewDialog;
import com.zl.tcbnewcar.utils.API;
import com.zl.tcbnewcar.utils.HttpUtils;
import com.zl.tcbnewcar.utils.ImageLoader;
import com.zl.tcbnewcar.utils.ShareUtils;
import com.zl.tcbnewcar.utils.SpUtlis;
import com.zl.tcbnewcar.utils.StringUtils;
import com.zl.tcbnewcar.utils.SystemUtils;
import com.zl.tcbnewcar.view.LocalServiceImageHolderView;
import com.zl.tcbnewcar.view.MyListView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author zhanglei
 * @date 18/3/20
 */
public class ServiceDetailActivity extends BaseActivity {

    @BindView(R.id.iv_title_back)
    ImageView ivTitleBack;
    @BindView(R.id.tv_title_name)
    TextView tvTitleName;
    @BindView(R.id.iv_title_share)
    ImageView ivTitleShare;
    @BindView(R.id.tv_title_right)
    TextView tvTitleRight;
    @BindView(R.id.service_banner)
    ConvenientBanner serviceBanner;
    @BindView(R.id.tv_serviceCollectionCount)
    TextView tvServiceCollectionCount;
    @BindView(R.id.iv_isFollowDetails)
    ImageView ivIsFollowDetails;
    @BindView(R.id.iv_service_hang_icon)
    ImageView ivServiceHangIcon;
    @BindView(R.id.tv_service_hang_name)
    TextView tvServiceHangName;
    @BindView(R.id.tv_service_data)
    TextView tvServiceData;
    @BindView(R.id.tv_service_hang_person)
    TextView tvServiceHangPerson;
    @BindView(R.id.tv_service_person_phone)
    TextView tvServicePersonPhone;
    @BindView(R.id.iv_call)
    ImageView ivCall;
    @BindView(R.id.service_tab)
    TabLayout serviceTab;
    @BindView(R.id.tv_service_content)
    TextView tvServiceContent;
    @BindView(R.id.service_linear)
    AutoLinearLayout serviceLinear;
    @BindView(R.id.tv_info_more_discuss)
    TextView tvInfoMoreDiscuss;
    @BindView(R.id.discuss_listView)
    MyListView discussListView;
    @BindView(R.id.tv_to_discuss)
    TextView tvToDiscuss;
    @BindView(R.id.linear_dis)
    AutoLinearLayout linearDis;
    @BindView(R.id.service_scroll_trl)
    TwinklingRefreshLayout serviceScrollTrl;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    private int sid;
    private ImagePreviewDialog previewDialog;
    private List<CarServerResourceEntity> bList = new ArrayList<>();
    private List<CarCommentEntity> disList = new ArrayList<>();
    private UniversalAdapter<CarCommentEntity> disAdapter;
    private CarServerEntity carServerEntity;
    private boolean isFollowDetails;
    private int followCount;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_service_detail);
        ButterKnife.bind(this);
        initView();
        initData();
        initListener();
    }

    private void initListener() {
        serviceTab.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                switch (tab.getPosition()) {
                    case 0:
                        linearDis.setVisibility(View.GONE);
                        serviceLinear.setVisibility(View.VISIBLE);
                        break;
                    case 1:
                        linearDis.setVisibility(View.VISIBLE);
                        serviceLinear.setVisibility(View.GONE);
                        break;
                }
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
        serviceBanner.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(int position) {
                if (carServerEntity == null) {
                    return;
                }
                List<CarServerResourceEntity> resources = carServerEntity.getResources();
                List<String> list = new ArrayList<String>();
                for (CarServerResourceEntity resource : resources) {
                    list.add(resource.getResServerUrl());
                }
                previewDialog.setData(list);
                previewDialog.showDialog(linearDis);
            }
        });
    }

    private void initData() {
        sid = getIntent().getIntExtra("sid", 0);
        getUiData();
        isSubscribeService();
    }

    @Override
    protected void onResume() {
        super.onResume();
        getListData();
    }

    /**
     * 订阅服务
     */
    private void shouCang() {
        if (carServerEntity == null) return;
        Map<String, String> params = new HashMap<>();
        params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
        params.put("sid", sid + "");

        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            builder.add(entry.getKey(), entry.getValue());
        }
        //创建请求体
        Request request = new Request.Builder().url(API.subscriceServer).post(builder.build()).build();

        //加入任务调度
        new OkHttpClient.Builder().build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                final String string = response.body().string();
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(string);
                            if (jsonObject.optString("msg").equals("已订阅")) {
                                followCount += 1;
                                tvServiceCollectionCount.setText("热度  " + followCount + "");
                                isFollowDetails = true;
                            } else {
                                followCount -= 1;
                                tvServiceCollectionCount.setText("热度  " + followCount + "");
                                isFollowDetails = false;
                            }
                            if (isFollowDetails) {
                                ivIsFollowDetails.setImageResource(R.drawable.ic_favorite_white);
                            } else {
                                ivIsFollowDetails.setImageResource(R.drawable.ic_favorite_border_white);
                            }
                        } catch (Exception e) {
                            showToast("发生了未知错误");
                        }
                    }
                });
            }
        });
    }

    /**
     * 是否关注了该服务
     */
    private void isSubscribeService() {
        Map<String, String> params = new HashMap<>();
        params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
        params.put("sid", sid + "");
        FormBody.Builder builder = new FormBody.Builder();
        Set<Map.Entry<String, String>> entries = params.entrySet();
        for (Map.Entry<String, String> entry : entries) {
            builder.add(entry.getKey(), entry.getValue());
        }
        //创建请求体
        Request request = new Request.Builder().url(API.isSubscriceDetails).post(builder.build()).build();

        //加入任务调度
        new OkHttpClient.Builder().build().newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(final Call call, final IOException e) {
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {

                    }
                });
            }

            @Override
            public void onResponse(final Call call, final Response response) throws IOException {
                final String string = response.body().string();
                mActivity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            JSONObject jsonObject = new JSONObject(string);
                            isFollowDetails = jsonObject.optBoolean("result");
                            if (isFollowDetails) {
                                ivIsFollowDetails.setImageResource(R.drawable.ic_favorite_white);
                            } else {
                                ivIsFollowDetails.setImageResource(R.drawable.ic_favorite_border_white);
                            }
                        } catch (Exception e) {
                            showToast("发生了未知错误");
                        }
                    }
                });
            }
        });
    }

    /**
     * 获取界面数据
     */
    private void getUiData() {
        Map<String, String> params = new HashMap<>();
        params.put("sid", sid + "");
        params.put("isSee", true + "");
        HttpUtils.getInstance().Post(mActivity, params, API.getServerInfoById, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                carServerEntity = new Gson().fromJson(body, CarServerEntity.class);
                updateUi(carServerEntity);
            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    //获取评论数据
    private void getListData() {
        Map<String, String> params = new HashMap<>();
        params.put("sid", sid + "");
        params.put("page", "1");
        HttpUtils.getInstance().Post(mActivity, params, API.carServerCommentShowList, new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
                try {
                    disList.clear();
                    JSONObject object = new JSONObject(body);
                    JSONArray array = new JSONArray(object.optString("items"));
                    for (int i = 0; i < (array.length() > 5 ? 5 : array.length()); i++) {
                        disList.add(new Gson().fromJson(array.optString(i), CarCommentEntity.class));
                    }
                    disAdapter.notifyDataSetChanged();

                    if (disList.size() <= 0) {
                        tvToDiscuss.setVisibility(View.VISIBLE);
                    } else {
                        tvToDiscuss.setVisibility(View.GONE);
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });
    }

    /**
     * 得到数据更新UI
     *
     * @param carServerEntity
     */
    private void updateUi(CarServerEntity carServerEntity) {
        ImageLoader.loadImageUrl(mActivity, carServerEntity.getSerImg(), ivServiceHangIcon);
        tvServiceHangName.setText(carServerEntity.getSerTitle());
        tvServiceData.setText("地区：" + carServerEntity.getCity().getCityName());
        tvServiceHangPerson.setText("联系人：" + carServerEntity.getSerUserName());
        tvServicePersonPhone.setText("联系方式：" + carServerEntity.getSerUserPhone());
        tvAddress.setText("详细地址：" + carServerEntity.getSerAddress());

        //轮播图
        bList.addAll(carServerEntity.getResources());
        //自定义你的Holder，实现更多复杂的界面，不一定是图片翻页，其他任何控件翻页亦可。
        serviceBanner.setPages(
                new CBViewHolderCreator<LocalServiceImageHolderView>() {
                    @Override
                    public LocalServiceImageHolderView createHolder() {
                        return new LocalServiceImageHolderView();
                    }
                }, bList);

        tvServiceContent.setText(carServerEntity.getSerContext());
        tvServiceCollectionCount.setText("热度：" + carServerEntity.getSerSubscrice());
        followCount = carServerEntity.getSerSubscrice();
    }

    private void initView() {
        tvTitleName.setText("服务详情");

        serviceTab.addTab(serviceTab.newTab().setText("服务描述"));
        serviceTab.addTab(serviceTab.newTab().setText("服务评论"));
        ivTitleShare.setVisibility(View.VISIBLE);
        previewDialog = new ImagePreviewDialog(mActivity);


        initBanner(serviceBanner);

        serviceScrollTrl.setEnableRefresh(false);
        serviceScrollTrl.setEnableLoadmore(false);

        disAdapter = new UniversalAdapter<CarCommentEntity>(mActivity, disList, R.layout.discuss_list_item) {
            @Override
            public void convert(UniversalViewHolder holder, int position, CarCommentEntity s) {
                holder.setText(R.id.tv_dis_data, s.getCommContext());
                holder.setText(R.id.tv_person_name, TextUtils.isEmpty(s.getCarUserEntity().getUserName()) ?
                        s.getCarUserEntity().getUserNikeName() : s.getCarUserEntity().getUserName());
                holder.setText(R.id.tv_discuss_date, StringUtils.dateYYYY_MM_DD_HH_mm_ss(s.getCommDate()));
                holder.setImageUrl(mActivity, R.id.iv_person_icon, s.getCarUserEntity().getUserImg());
            }
        };
        discussListView.setAdapter(disAdapter);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        UMShareAPI.get(mActivity).onActivityResult(requestCode, resultCode, data);
    }

    @OnClick({R.id.iv_title_back, R.id.iv_call, R.id.iv_title_share, R.id.tv_info_more_discuss, R.id.tv_to_discuss, R.id.iv_isFollowDetails})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.iv_title_back:
                finish();
                break;
            case R.id.iv_call:
                if (carServerEntity == null) return;
                SystemUtils.call(mActivity, carServerEntity.getSerUserPhone());
                break;
            case R.id.tv_info_more_discuss:
                Intent intent = new Intent(mActivity, ServiceDiscussActivity.class);
                intent.putExtra("sid", carServerEntity.getId());
                startActivity(intent);
                break;
            case R.id.tv_to_discuss:
                Intent intent1 = new Intent(mActivity, ServiceDiscussActivity.class);
                intent1.putExtra("sid", carServerEntity.getId());
                startActivity(intent1);
                break;
            case R.id.iv_title_share:
                share();
                break;
            case R.id.iv_isFollowDetails:
                shouCang();
                break;
        }
    }

    private void share() {
        if (carServerEntity == null) return;
        ShareBean shareBean = new ShareBean();
        shareBean.setShareTitle(carServerEntity.getSerTitle());
        shareBean.setImgUrl(carServerEntity.getSerImg());
        shareBean.setShareContent(carServerEntity.getSerContext());
        shareBean.setUrl(API.toCarServer + "?sid=" + carServerEntity.getId());
        ShareUtils.share(mActivity, shareBean, new ShareUtils.OnShareListener() {
            @Override
            public void shareSuccess(SHARE_MEDIA share_media) {
                showToast("分享成功");
                Map<String, String> params = new HashMap<String, String>();
//                params.put("uid", SpUtlis.getUserData(mActivity).getId() + "");
                params.put("sid", carServerEntity.getId() + "");
                HttpUtils.getInstance().Post(mActivity, params, API.toForwardServer, new HttpUtils.OnOkHttpCallback() {
                    @Override
                    public void onSuccess(String body) {
                        Log.e("body", body);
                    }

                    @Override
                    public void onError(Request error, Exception e) {
                        Log.e("body", "");
                    }
                });
            }

            @Override
            public void shareError(SHARE_MEDIA share_media, Throwable throwable) {

            }
        });
    }
}
